<HTML>
<HEAD>
	<TITLE>Test</TITLE>
	<script type="text/javascript" src="../opesoft/js/frame.js" /></script>
	<SCRIPT LANGUAGE="JavaScript">
	<!--
		$include("js/ajax.js");
	//-->
	</SCRIPT>

<SCRIPT LANGUAGE="JavaScript">
<!--
/*
	function toString(obj){
		switch($type(obj)){
			case 'string':
				return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
			case 'array':
				return '[' + obj.map(Json.toString).join(',') + ']';
			case 'object':
				var string = [];
				for (var property in obj) string.push(Json.toString(property) + ':' + Json.toString(obj[property]));
				return '{' + string.join(',') + '}';
			case 'number':
				if (isFinite(obj)) break;
			case false:
				return 'null';
		}
		return String(obj);
	}
*/

function JsonBuilder(stack)
{
	this.stack=stack==null?{}:stack;
	this.index=0;

	this.i=0;
}

JsonBuilder.prototype.toString=function(obj)
{
	switch($type(obj))
	{
		case 'object':
			if(obj['class'])
			{
				var clazz=obj['class'];
				if(this.stack[clazz])
					return Json.toString({'class':clazz});
				else
				{
					this.stack[clazz]=obj;
					this.index++;
					var string=[];
					for (var property in obj) string.push(this.toString(property) + ':' + this.toString(obj[property]));
					return '{' + string.join(',') + '}';
				}
			}
	}

	return Json.toString(obj)
}

JsonBuilder.prototype.toObject=function(str)
{
	var obj=Json.evaluate(str)
	this._toObject(obj);
	return obj;
}

JsonBuilder.prototype._toObject=function(obj)
{
	if(obj!=null)// && $type(obj)=="object")
	{
		if(obj['class'] && this.stack[obj['class']]==null)
			this.stack[obj['class']]=obj;
		
		if($type(obj)=="object")
		{
			for(k in obj)
			{
				var clazz=obj[k]['class'];
				if(clazz!=null && this.stack[clazz]!=null)
						obj[k]=this.stack[clazz];
				else
						this._toObject(obj[k]);
			}
		}
		else if($type(obj)=="array")
		{
			for(var i=0;i<obj.length;i++)
			{
				var clazz=obj[i]['class'];
				if(clazz!=null && this.stack[clazz]!=null)
					obj[i]=this.stack[clazz];
				else
					this.toObject(obj[i]);
			}
		}
	}
}

var a={name:'a','class':'A@1'};
var b={name:'b','class':'B@1'};
b["friend"]=a;
a["friend"]=b;
var n=6;

var jb=new JsonBuilder();
var str=jb.toString(b);
$debug(str);

jb=new JsonBuilder();
var obj=jb.toObject(str);
$debug(obj.friend.friend==obj);

//-->
</SCRIPT>
</HEAD>
<BODY>




</BODY>
</HTML>